package com.lysj.bhp.coinexchange.service;

import com.lysj.bhp.coinexchange.base.CoinExchangeContent;
import com.lysj.bhp.coinexchange.domain.BhpcRecord;
import com.lysj.bhp.investment.domain.Reward;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

@Service
@Transactional
public class ExchangeBhpcBounsService extends CoinExchangeContent {

    public Resp exchangeBhpcBouns(BigDecimal exchangeNum, int type, String tradePassword){
        if (ParamUtil.isBlack(tradePassword)) {
            return new Resp(Resp.PARAM_ERROR, "请输入交易密码");
        }
        if (!ParamUtil.md5(tradePassword).equals(currentUser().getTradePassword())) {
            return new Resp(Resp.PARAM_ERROR, "交易密码错误");
        }
        if (exchangeNum.compareTo(BigDecimal.ZERO) != 1) {
            return new Resp(Resp.PARAM_ERROR, "兑换数额必须大于0");
        }
        if (exchangeNum.compareTo(currentUser().getDividend()) == 1) {
            return new Resp(Resp.PARAM_ERROR, "兑换数额超过可用余额");
        }
        //判定兑换成的bhpc数额是否大于1
        BigDecimal ethToDollar = exchangeNum.multiply(exchangeRateService.getEthereumToDollar()).setScale(6, BigDecimal.ROUND_HALF_UP);
        BigDecimal ethToBhpc = ethToDollar.divide(exchangeRateService.getBhpcToDollar(), 6, BigDecimal.ROUND_HALF_UP);
        if (ethToBhpc.compareTo(new BigDecimal("1")) == -1) {
            return new Resp(Resp.PARAM_ERROR, "兑换目标数量至少1个BHPC");
        }
        //获取当前用户的奖励表,若不存在则给用户创建
        Reward reward = rewardRepository.findByUserId(currentUser().getUserId());
        if (null == reward) {
            reward = new Reward();
            reward.setUserId(currentUser().getUserId());
            reward.setType(100);
            reward.setBalance(new BigDecimal(BigInteger.ZERO));
            reward.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            reward.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
        }
        //更改用户的总利息和奖励表数额
        currentUser().setDividend(currentUser().getDividend().subtract(exchangeNum));
        reward.setAvailBalance(reward.getAvailBalance().add(ethToBhpc));
        reward.setBalance(reward.getBalance().add(ethToBhpc));
        //创建bhpc记录表
        BhpcRecord bhpcRecord = new BhpcRecord();
        bhpcRecord.setUserId(currentUser().getUserId());
        bhpcRecord.setExchangeNum(exchangeNum);
        bhpcRecord.setExchangeRate(exchangeRateService.getEthereumToDollar());
        bhpcRecord.setType(type);
        bhpcRecord.setBhpcToDollar(exchangeRateService.getBhpcToDollar());
        bhpcRecord.setCreateDate(new Date());
        bhpcRecord.setStatus("成功");
        bhpcRecord.setBhpc(ethToBhpc); //通过计算获得Bhpc的数量
        bhpcRecordRepository.save(bhpcRecord);
        userRepository.save(currentUser());
        rewardRepository.save(reward);
        return new Resp("提取成功");
    }
}
